<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Authenticate extends CI_Controller {

    public function __construct()
	{
		parent::__construct(); 
		$this->load->model('system/user_m','user_m',TRUE);
		$this->load->library('json');
		$this->load->helper('cookie');
	}
	
	public function index()
	{
		$salt = $this->config->item('salt');
	    
	    $payload = $this->input->post('payload');
        $data = json_decode($payload);
		
		$username = $data->username;
		$password = $data->password;
		$remember = $data->remember;
		
		if($remember==1){
		   // Save username and password to cookie
		   set_cookie(AUTH_COOKIE,"$username|".md5($salt.$password),time()+3.156e+12);
		}
		

		header("Content-type: application/json");
		$auth_result = $this->user_m->authenticate($username,$salt . $password);
		if( $auth_result == 0 ){
		   // Sukses
		   // Simpan ke SESSION
		   $userdata = array(
		                    LOGGEDUSERNAME => $username
		               );
		   
		   $this->session->set_userdata($userdata);
		   			   
		   echo $this->json->ok();
		   
		} else  if( $auth_result == -1 ){
  		   echo $this->json->fail('Username and password did not match');
		} else  if( $auth_result == -2 ){
  		   echo $this->json->fail('Your account is not yet activated. Please check your email or <a href="./common/activation/resend">click here to resend</a>');
		}
	}
	
}

/* End of file authenticate.php */
/* Location: ./application/controllers/ajax/authenticate.php */